package com.opensky.qatest.ui.page;

import java.util.List;

import junit.framework.Assert;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.LoadableComponent;

import com.opensky.qatest.util.common.LogicUtils;
import com.opensky.qatest.util.selenium.Report;
import com.opensky.qatest.util.selenium.WebDriverWrapper;

public class ManageCuratorsPage extends LoadableComponent<ManageCuratorsPage> implements IPage {

    // ************************ Locators ************************

    private static final String MANAGE_CURATORS_PAGE_URL = "https://opensky.com/following";

    private static final String UNFOLLOW_BTN = "//aside//input[@name='unfollow']";

    public static final long TIMEOUT = 3;

    private final WebDriverWrapper driver;

    public ManageCuratorsPage(WebDriverWrapper driver) {
	this.driver = driver;
    }

    // ************************ Actions **************************

    @Override
    protected void load() {
	driver.get(MANAGE_CURATORS_PAGE_URL);
    }

    // ************************ Validations **************************

    @Override
    protected void isLoaded() throws Error {
	String url = driver.getCurrentUrl();
	Assert.assertTrue(Report.wrongURL(MANAGE_CURATORS_PAGE_URL, url), LogicUtils.isURLEqual(MANAGE_CURATORS_PAGE_URL, url));
    }

    public boolean isPageLoaded() {
	return driver.waitAndVerifyURL(MANAGE_CURATORS_PAGE_URL);
    }

    public void unfollowAllButOneCurator() {
	List<WebElement> unfollowBtns = driver.waitAssertAndGetElements("UNFOLLOW_BTN", By.xpath(UNFOLLOW_BTN));

	if (unfollowBtns != null && unfollowBtns.get(0) != null) {
	    unfollowBtns.remove(0);

	    for (WebElement btn : unfollowBtns) {
		btn.click();
		driver.pause(TIMEOUT);
	    }
	}
    }

    @Override
    public String getName() {
	return "Manage curators page";
    }
}
